package com.v2future.sjt.collegecheckingattendance.personal;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.library.Constant;
import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.fruit.AddFruitActivity;
import com.v2future.sjt.collegecheckingattendance.fruit.FruitOneTypeActivity;
import com.v2future.sjt.collegecheckingattendance.fruit.bean.ConditionTypeBean;
import com.v2future.sjt.collegecheckingattendance.home.HomeActivity;
import com.v2future.sjt.collegecheckingattendance.home.bean.LoginResultBean;
import com.v2future.sjt.collegecheckingattendance.personal.bean.OnePolicitsBean;
import com.v2future.sjt.collegecheckingattendance.personal.bean.UserInfoBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.SessionSelectDialog;

import org.xutils.x;

import java.io.File;
import java.io.Serializable;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 基本信息
 * @author shijianting
 * @time 2016/4/16 13:19
 */
public class BasicInfoActivity extends MainActivity implements View.OnClickListener{

    /**
     * 名字
     */
    private TextView nameTv;

    private EditText classEt,roomEt,contactEt;

    private Button politicsBtn;

    private LinearLayout headLayout;

    private ImageView headIv;

    private LinearLayout fruitLayout;

    private LinearLayout nameLayout,classLayout,roomLayout,politicsLayout,contactLayout;

    /**
     * 寝室编辑layout
     */
    private LinearLayout roomEditLayout;

    /**
     * 寝室编辑中的“栋”
     */
    private EditText dongEt;

    /**
     * 寝室编辑中的寝室号
     */
    private EditText roomIdEt;

    /**
     * 场次时间选择对话框
     */
    private SessionSelectDialog sesstionDialog;

    int REQUEST_IMAGE = 1001;

    String imagePath;

    public static final String INTENT_TAG_HEAD_ID = "head_id";

    private final String EDIT = "编辑";
    private final String SAVE = "保存";

    int userIdentity;//用户身份

    /**
     * 所有的政治面貌
     */
    private List<OnePolicitsBean> policitsList;

    /**
     * 选中的政治面貌
     */
    private OnePolicitsBean selectPolicts;

    @Override
    public void init() {

    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_basic_info);
        initTitleBack(null);
        setTitleText(getString(R.string.base_info));
        nameTv = (TextView) findViewById(R.id.tv_name);
        classEt = (EditText) findViewById(R.id.et_class);
        roomEt = (EditText) findViewById(R.id.et_room);
        politicsBtn = (Button) findViewById(R.id.btn_politics);
        contactEt = (EditText) findViewById(R.id.et_contact);
        fruitLayout = (LinearLayout) findViewById(R.id.layout_fruit);
        fruitLayout.setOnClickListener(this);
        nameLayout = (LinearLayout) findViewById(R.id.layout_name);
        classLayout = (LinearLayout) findViewById(R.id.layout_class);
        roomLayout = (LinearLayout) findViewById(R.id.layout_room);
        politicsLayout = (LinearLayout) findViewById(R.id.layout_politics);
        contactLayout = (LinearLayout) findViewById(R.id.layout_contact);
        roomEditLayout = (LinearLayout) findViewById(R.id.layout_room_edit);
        roomIdEt = (EditText) findViewById(R.id.et_room_id);
        dongEt = (EditText) findViewById(R.id.et_dong);
    }

    @Override
    public void initAfter() {
        setRightText(EDIT, editInfoListener);
        initUserView();
        doGetUserInfo();
        doGetPoliticalType(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LoginResultBean userInfo = getUserInfo();
        if (null != userInfo) {
            if (!TextUtils.isEmpty(userInfo.getData().getUserName())) {
                nameTv.setText(userInfo.getData().getUserName());
            }
        }
    }

    /**
     * 刷新用户信息
     * @param bean
     */
    private void refreshUserInfo(UserInfoBean bean){
        nameTv.setText(bean.getUserName());
        classEt.setText(bean.getClassName());
        roomEt.setText(bean.getDormitory().replace("#", "栋"));
        politicsBtn.setText(bean.getPoliticalName());
        contactEt.setText(bean.getUserMobile());
    }

    /**
     * 根据身份初始化界面
     */
    private void initUserView(){
         userIdentity = 0 ;
        if (null != getUserInfo() && !TextUtils.isEmpty(getUserInfo().getData().getSourceTypeId())) {
            userIdentity = Integer.parseInt(getUserInfo().getData().getSourceTypeId());
        }
        if (HomeActivity.TEACHER == userIdentity) {
            selectPolicts = new OnePolicitsBean();
            selectPolicts.setPolitical("1");
            classLayout.setVisibility(View.GONE);
            politicsLayout.setVisibility(View.GONE);
            roomLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 修改用户信息
     * @param dormitory
     * @param political
     */
    public void doModifyUserInfo(final String dormitory, final String political, final String userMobile){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.MODIFY_USER_INFO));
        params.addQueryStringParameter("dormitory", dormitory);
        params.addQueryStringParameter("political", political);
        params.addQueryStringParameter("userMobile", userMobile);
        NetUtils.doGetRequest(this, params, new NetTaskListener<BaseResponseBean>() {

            @Override
            public void onSuccess(BaseResponseBean result) {
                showSimpleDialog("修改信息完成");
                doGetUserInfo();
                changeToNormalStatus();
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * 获取政治面貌
     */
    public void doGetPoliticalType(final boolean isShowDialog){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_POLITICS));
        NetUtils.doGetRequest(this, params, new NetTaskListener<PolicitsResponseBean>() {

            @Override
            public void onSuccess(PolicitsResponseBean result) {
                policitsList = result.getData();
                if (isShowDialog) showPoliticsWindow();
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(PolicitsResponseBean result) {
                tip(result.getFailReason());
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(PolicitsResponseBean result) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    private void doGetUserInfo(){
        BaseRequestParams params = new BaseRequestParams(this, formatUrl(Constants.GET_USER_INFO));
        String userType = getUserInfo().getData().getSourceTypeId();
        if (TextUtils.isEmpty(userType)) {
            tip("用户身份有误");
            return;
        }
        params.addQueryStringParameter("sourceTypeId", userType);
        NetUtils.doGetRequest(this, params, new NetTaskListener<UserInfoResponseBean>() {

            @Override
            public void onSuccess(UserInfoResponseBean result) {
                refreshUserInfo(result.getData());
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(UserInfoResponseBean result) {

            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {

            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccessCache(UserInfoResponseBean result) {

            }
        });
    }

    /**
     * 展示政治面貌选择界面
     */
    private void showPoliticsWindow() {
        if (null != sesstionDialog) {
            sesstionDialog.show();
        } else {
            sesstionDialog = new SessionSelectDialog(this, R.style.Dialog_sesseion, policitsList, new SessionSelectDialog.ClickListener() {
                @Override
                public void selecData(OnePolicitsBean date, int position) {
                    selectPolicts = date;
                    politicsBtn.setText(selectPolicts.getPoliticalName());
                }
            });
            sesstionDialog.setCancelable(true);
            sesstionDialog.show();
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_fruit://获奖成果点击
                ConditionTypeBean conditionTypeBean = new ConditionTypeBean();
                conditionTypeBean.setConditonTypeId("5");
                conditionTypeBean.setConditonTypeName("获奖成果");
                Intent intent = new Intent(BasicInfoActivity.this, FruitOneTypeActivity.class);
                intent.putExtra(IntentKey.FRUIT_TYPE, conditionTypeBean);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 编辑个人信息事件
     */
    private View.OnClickListener editInfoListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeToEditStatus();
        }
    };

    /**
     * 转换到编辑状态
     */
    private void changeToEditStatus(){
        setRightText(SAVE, saveInfoListener);
        /**
         * 寝室
         */
        roomEt.setEnabled(true);
        String roomStr = roomEt.getText().toString().trim();
        if (TextUtils.isEmpty(roomStr) || "-".equals(roomStr)) {
            roomEt.setText("");
        }
        roomEt.setVisibility(View.GONE);
        roomEditLayout.setVisibility(View.VISIBLE);
        politicsBtn.setEnabled(true);
        String politicsStr = roomEt.getText().toString().trim();
        if (TextUtils.isEmpty(politicsStr) || "-".equals(politicsStr)) {
            politicsBtn.setText("");
        }
        politicsBtn.setOnClickListener(politicsListener);
        contactEt.setEnabled(true);
        String contactStr = roomEt.getText().toString().trim();
        if (TextUtils.isEmpty(contactStr) || "-".equals(contactStr)) {
            contactEt.setText("");
        }
    }

    /**
     * 转换到普通状态
     */
    private void changeToNormalStatus(){
        setRightText(EDIT, editInfoListener);
        roomEt.setEnabled(false);
        politicsBtn.setEnabled(false);
        contactEt.setEnabled(false);
        roomEt.setVisibility(View.VISIBLE);
        roomEditLayout.setVisibility(View.GONE);
    }

    /**
     * 保存个人信息事件
     */
    private View.OnClickListener saveInfoListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (null == selectPolicts && (TextUtils.isEmpty(politicsBtn.getText().toString().trim()) || "".equals(politicsBtn.getText().toString().trim()))) {
                tip("请完成填写信息");
                return;
            }
            String roomStr = dongEt.getText().toString() + "#" + roomIdEt.getText().toString();
            String politicsId;
            if (null != selectPolicts && null != selectPolicts.getPolitical()) {
                politicsId = selectPolicts.getPolitical();
            }
            else {
                politicsId = getPolictsId(politicsBtn.getText().toString());
            }
            String contactStr = contactEt.getText().toString();
            if (HomeActivity.STUDENT == userIdentity && (TextUtils.isEmpty(roomStr) || TextUtils.isEmpty(politicsId)
                    || TextUtils.isEmpty(contactStr)) || TextUtils.isEmpty(dongEt.getText()) || TextUtils.isEmpty(roomIdEt.getText().toString())) {
                tip("请完成填写信息");
                return;
            }
            else if (HomeActivity.TEACHER == userIdentity && TextUtils.isEmpty(contactStr)) {
                tip("请完成填写信息");
                return;
            }
            showLoadingDialog();
            doModifyUserInfo(roomStr, politicsId, contactStr);
        }
    };

    /**
     * 根据文本内容查找政治面貌id
     * @param polictsStr
     * @return
     */
    private String getPolictsId(String polictsStr){
        if (policitsList == null || policitsList.size() ==0) return null;
        for (OnePolicitsBean bean:policitsList
             ) {
            if (bean.getPoliticalName().equals(polictsStr)) return bean.getPolitical();
        }
        return null;
    }

    /**
     * 政治面貌事件
     */
    private View.OnClickListener politicsListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showLoadingDialog();
            doGetPoliticalType(true);
        }
    };

    /**
     * 政治面貌回复
     */
    private class PolicitsResponseBean  extends BaseResponseBean implements Serializable {
        private List<OnePolicitsBean> data;

        public List<OnePolicitsBean> getData() {
            return data;
        }

        public void setData(List<OnePolicitsBean> data) {
            this.data = data;
        }
    }

    /**
     * 用户信息回复
     */
    private class UserInfoResponseBean extends BaseResponseBean implements Serializable {

        private UserInfoBean data;

        public UserInfoBean getData() {
            return data;
        }

        public void setData(UserInfoBean data) {
            this.data = data;
        }
    }
}
